<template>
  <div class="admin-login">
    <div class="login-container">
      <div class="login-card">
        <div class="login-header">
          <h2>管理员登录</h2>
          <p>请输入管理员账号和密码</p>
        </div>

        <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="User" size="large" />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="密码"
              prefix-icon="Lock"
              size="large"
              show-password
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" size="large" :loading="loading" @click="handleLogin" style="width: 100%">
              登录
            </el-button>
          </el-form-item>
        </el-form>

        <div class="login-footer">
          <el-link @click="goBack">返回用户端</el-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { adminLogin } from "@/api/admin";
import { authManager, UserRole } from "@/utils/auth";
import { logger } from "@/utils/logger";

const router = useRouter();
const loginFormRef = ref();
const loading = ref(false);

const loginForm = reactive({
  username: "",
  password: "",
});

const loginRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
};

const handleLogin = async () => {
  try {
    await loginFormRef.value.validate();
    loading.value = true;

    // 调用登录API
    const response = await adminLogin(loginForm);

    if (response.data.success) {
      const { token, user } = response.data;

      // 设置用户信息和token
      const authUser = {
        id: user.id,
        username: user.username,
        email: user.email,
        role: UserRole.ADMIN,
        permissions: authManager.generateUserPermissions(UserRole.ADMIN),
        isActive: true,
        lastLoginTime: new Date().toISOString(),
      };

      authManager.setCurrentUser(authUser);
      authManager.setToken(token);

      // 记录登录日志
      logger.info("管理员登录成功", {
        userId: user.id,
        username: user.username,
        ip: "127.0.0.1",
      });

      ElMessage.success("登录成功");
      router.push("/admin");
    } else {
      ElMessage.error(response.data.message || "登录失败");
    }
  } catch (error: any) {
    logger.error("管理员登录失败", error, {
      username: loginForm.username,
    });
    ElMessage.error("登录失败，请检查用户名和密码");
  } finally {
    loading.value = false;
  }
};

const goBack = () => {
  router.push("/");
};
</script>

<style lang="less" scoped>
.admin-login {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;

  .login-container {
    width: 100%;
    max-width: 400px;
    padding: 20px;

    .login-card {
      background: white;
      border-radius: 12px;
      padding: 40px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);

      .login-header {
        text-align: center;
        margin-bottom: 30px;

        h2 {
          color: #333;
          margin-bottom: 10px;
        }

        p {
          color: #666;
          font-size: 14px;
        }
      }

      .login-form {
        margin-bottom: 20px;
      }

      .login-footer {
        text-align: center;
        padding-top: 20px;
        border-top: 1px solid #eee;
      }
    }
  }
}
</style>
